import React, { useEffect, useState, createRef } from 'react'

import img from './assets/1.gif'

// 通过useState提供状态
// 通过useEffect给document注册鼠标移动事件
// 在组件销毁的时候清理副作用

export default function Mouse () {

    const [position, setPosition] = useState({
        x: 0,
        y: 0
    })

    const imgDom = createRef()

    useEffect(() => {

        console.log(document.getElementById('img'))
        console.dir(imgDom.current)


        const fn = (e) => {

            setPosition({ x: e.pageX, y: e.pageY })
            let img = document.getElementById('img')
            img.style.left = e.pageX + 'px'
            img.style.top = e.pageY + 'px'



        }
        window.addEventListener('mousemove', fn)
        return () => {
            window.removeEventListener('mousemove', fn)
        }
    }, [])

    return (
        <div>Mouse
            <hr />

            X:   {position.x}---------- y: {position.y}
            <hr />
            {/* <img src={img} alt="" style={{ width: '300px', borderRadius: '50%', position: 'absolute', left: position.x, top: position.y }} id='img'
                ref={imgDom}
            /> */}
            <img src={img} alt="" style={{ width: '300px', borderRadius: '50%', position: 'absolute' }}
                id='img'
                ref={imgDom}
            />

        </div>
    )
}
